package main

import (
	"context"
	"fmt"
	"github.com/apache/rocketmq-client-go/v2/consumer"
	"github.com/apache/rocketmq-client-go/v2/primitive"
	"time"
)

func main() {

	// Consumer配置
	c, _ := consumer.NewPushConsumer(
		consumer.WithGroupName("TestGroup"),
		consumer.WithNsResolver(primitive.NewPassthroughResolver([]string{"127.0.0.1:9876"})),
		consumer.WithConsumeFromWhere(consumer.ConsumeFromFirstOffset),
		consumer.WithConsumerModel(consumer.Clustering),
		consumer.WithMaxReconsumeTimes(3), // 设置最大重试次数
	)
	err := c.Subscribe("TestTopic", consumer.MessageSelector{}, func(ctx context.Context, msgs ...*primitive.MessageExt) (consumer.ConsumeResult, error) {
		for _, msg := range msgs {
			fmt.Printf("Receive message: %s\n", msg)
			// 这里模拟消息处理失败
			return consumer.ConsumeRetryLater, nil
		}
		return consumer.ConsumeSuccess, nil
	})
	if err != nil {
		fmt.Println("Subscribe error:", err)
		return
	}

	// 启动Consumer
	err = c.Start()
	if err != nil {
		fmt.Println("Start consumer error:", err)
		return
	}
	defer c.Shutdown()

	// 为死信队列设置Consumer
	dlqConsumer, _ := consumer.NewPushConsumer(
		consumer.WithGroupName("DLQGroup"),
		consumer.WithNsResolver(primitive.NewPassthroughResolver([]string{"127.0.0.1:9876"})),
		consumer.WithConsumeFromWhere(consumer.ConsumeFromFirstOffset),
		consumer.WithConsumerModel(consumer.Clustering),
	)
	err = dlqConsumer.Subscribe("TestTopic_DLQ", consumer.MessageSelector{}, func(ctx context.Context, msgs ...*primitive.MessageExt) (consumer.ConsumeResult, error) {
		for _, msg := range msgs {
			fmt.Printf("Receive message from DLQ: %s\n", msg)
			// 处理死信队列中的消息
		}
		return consumer.ConsumeSuccess, nil
	})
	if err != nil {
		fmt.Println("Subscribe to DLQ error:", err)
		return
	}
	err = dlqConsumer.Start()
	if err != nil {
		fmt.Println("Start DLQ consumer error:", err)
		return
	}
	defer dlqConsumer.Shutdown()

	// 程序运行一段时间
	time.Sleep(10 * time.Second)
}
